<template>
  <div class="overflow-hidden px-10">
    <div class="head-title">登陆账号管理</div>
    <div class="form-content">
      <el-form ref="displayForm" :model="displayForm" class="w-1/2 m-auto">
        <el-form-item label="登陆手机号" prop="userName">
          <el-input
            type="number"
            placeholder="请输入登陆手机号"
            v-model="userName"
            readonly
          >
            <i slot="prefix" class="el-input__icon el-icon-user-solid"></i>
            <el-button
              slot="append"
              icon="el-icon-edit"
              @click.stop="open('phone')"
              >修改</el-button
            >
          </el-input>
        </el-form-item>

        <el-form-item label="登陆密码" prop="password">
          <el-input
            type="password"
            placeholder="请输入登陆密码"
            v-model="displayForm.password"
            readonly
          >
            <i slot="prefix" class="el-input__icon el-icon-more"></i>
            <el-button
              slot="append"
              icon="el-icon-edit"
              @click.stop="open('password')"
              >修改</el-button
            >
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="centerDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      @close="initDialog"
    >
      <!-- 验证身份 -->
      <el-form
        ref="validateForm"
        :model="validateForm"
        v-if="isOpenValidateDialog"
      >
        <div class="mb-4">
          为了保证账号安全，请使用手机尾号为{{
            userName.substring(userName.length - 4)
          }}的手机号进行身份验证。
        </div>

        <el-form-item label="" prop="code" class="code-input">
          <el-input
            type="number"
            maxlength="5"
            placeholder="请输入验证码"
            v-model="validateForm.code"
          >
            <i slot="prefix" class="el-input__icon el-icon-s-claim"></i>
            <el-button
              slot="append"
              type="info"
              :disabled="isGetcode"
              @click="getCode"
            >
              获取验证码{{ isGetcode ? "(" + countDown + ")" : "" }}
            </el-button>
          </el-input>
        </el-form-item>

        <el-button
          type="primary"
          :disabled="nextDisabled"
          class="w-full"
          @click="next"
          >下一步</el-button
        >
      </el-form>

      <!-- 更换手机号 -->
      <el-form
        ref="changePhoneForm"
        :model="changePhoneForm"
        v-if="isOpenChangePhone"
      >
        <el-form-item label="" prop="phonenumber">
          <el-input
            placeholder="请输入手机号"
            maxlength="11"
            v-model="changePhoneForm.phonenumber"
          >
            <i slot="prefix" class="el-input__icon el-icon-user-solid"></i>
          </el-input>
        </el-form-item>

        <el-form-item label="" prop="code">
          <el-input
            type="number"
            maxlength="5"
            placeholder="请输入验证码"
            v-model="changePhoneForm.code"
          >
            <i slot="prefix" class="el-input__icon el-icon-s-claim"></i>
            <el-button
              slot="append"
              type="info"
              :disabled="isGetcode"
              @click="getCode2"
            >
              获取验证码{{ isGetcode ? "(" + countDown + ")" : "" }}
            </el-button>
          </el-input>
        </el-form-item>

        <el-button type="primary" class="w-full" @click="changePhone"
          >确认</el-button
        >
      </el-form>

      <!-- 修改密码 -->
      <el-form
        ref="changePasswordForm"
        :model="changePasswordForm"
        :rules="changePasswordRules"
        v-if="isOpenChangePassword"
      >
        <el-form-item label="" prop="password">
          <el-input
            type="password"
            placeholder="请输入新密码, 密码长度为6-16位"
            show-password
            v-model="changePasswordForm.password"
          >
            <i slot="prefix" class="el-input__icon el-icon-more"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="" prop="confirmPassword">
          <el-input
            type="password"
            placeholder="请再次输入新密码, 密码长度为6-16位"
            show-password
            v-model="changePasswordForm.confirmPassword"
          >
            <i slot="prefix" class="el-input__icon el-icon-more"></i>
          </el-input>
        </el-form-item>
        <el-button type="primary" class="w-full" @click="changePassword"
          >确认</el-button
        >
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  removeBinding,
  forgetPwdgetCode,
  removeBindingPhone,
  bindingPhone,
  updateUserPhone,
  updatePassword
} from "@/api/personCenter/manageAccount";
// import { updatePassword } from "@/api/login";

export default {
  name: "manageAccount",
  components: {},
  data() {
    return {
      displayForm: {
        userName: "",
        password: "123456",
      },

      validateForm: {
        phone: "",
        code: "",
      },

      changePhoneForm: {
        phonenumber: "",
        code: "",
        formerlyPhone: "",
      },

      changePasswordForm: {
        password: "",
        confirmPassword: "",
      },

      // 当前打开的提示框类型
      dialogType: undefined,
      // 提示框标题
      title: "验证身份",
      // 验证提示框
      centerDialogVisible: false,

      // 验证码按钮是否可点击
      isGetcode: false,
      // 验证码限制时间
      countDown: 60,
      // 定时器
      setTimeDo: null,

      // 当前显示的表单内容
      isOpenValidateDialog: false,
      isOpenChangePhone: false,
      isOpenChangePassword: false,

      // 密码表单验证
      changePasswordRules: {
        password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, max: 16, message: "密码长度为6-16位", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入新密码", trigger: "blur" },
          { min: 6, max: 16, message: "密码长度为6-16位", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback();
              } else if (value !== this.changePasswordForm.password) {
                callback("两次输入的密码不一致");
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters({
      token: "token",
      userName: "name",
      phonenumber: "phonenumber",
    }),
    nextDisabled() {
      if (!this.validateForm.code) {
        return true;
      }
      return false;
    },
  },
  created() {},
  mounted() {},
  methods: {
    // 登出网站
    signOut() {
      this.$store.dispatch("LogOut").then((res) => {
        this.$router.push("/login");
      });
    },

    // 打开验证框
    open(type) {
      this.dialogType = type;
      this.isOpenValidateDialog = true;
      this.centerDialogVisible = true;
      // 清除定时器
      this.countDownFun(true);
      // 初始化表单数据
      this.initForm();
    },

    // 初始化所有弹出框状态
    initDialog() {
      this.isOpenValidateDialog = false;
      this.isOpenChangePhone = false;
      this.isOpenChangePassword = false;
      // 清除定时器
      this.countDownFun(true);
      // 初始化表单数据
      this.initForm();
    },

    // 初始化表单数据
    initForm() {
      this.validateForm.code = "";
      this.changePhoneForm.phonenumber = "";
      this.changePhoneForm.code = "";
      this.changePhoneForm.formerlyPhone = "";
      this.changePasswordForm.password = "";
      this.changePasswordForm.confirmPassword = "";
    },

    // 验证码倒计时
    countDownFun(isInit = false) {
      // 清除定时器
      if (isInit) {
        this.isGetcode = false;
        clearInterval(this.setTimeDo);
        return;
      }

      if (this.countDown == 60) {
        let that = this;
        this.setTimeDo = setInterval(() => {
          that.countDown--;

          if (that.countDown == 0) {
            if (this.setTimeDo) {
              this.countDown = 60;
              clearInterval(this.setTimeDo);
              that.isGetcode = false;
            }
          }
        }, 1000);
      }
    },

    // 确认手机号 获取验证码
    async getCode() {
      // 调用方法后 isGetcode  转为 true
      let phone = this.userName || undefined;
      let res = null;
      if (this.dialogType == "phone") {
        res = await removeBinding(phone);
      }
      if (this.dialogType == "password") {
        res = await forgetPwdgetCode(phone);
      }

      if (res.code == 200) {
        this.isGetcode = true;
        this.countDownFun();

        if (res.msg) {
          this.$message({
            type: "success",
            // message: '验证码已发送，请耐心等待',
            message: res.msg,
          });
        }
      }
    },
    getCode2() {
      // 调用方法后 isGetcode  转为 true
      let phone = this.changePhoneForm.phonenumber || undefined;
      bindingPhone(phone).then((res) => {
        if (res.code == 200) {
          this.isGetcode = true;
          this.countDownFun();

          if (res.msg) {
            this.$message({
              type: "success",
              // message: '验证码已发送，请耐心等待',
              message: res.msg,
            });
          }
        }
      });
    },

    // 下一步
    next() {
      if (this.dialogType == "password") {
        this.isOpenValidateDialog = false;
        this.isOpenChangePassword = true;
        this.title = "修改密码";
        return;
      }
      removeBindingPhone({
        phonenumber: this.userName,
        code: this.validateForm.code,
      }).then((res) => {
        if (res.code == 200) {
          this.isOpenValidateDialog = false;
          if (this.dialogType == "phone") {
            this.isOpenChangePhone = true;
            this.title = "更换手机号";
          } else if (this.dialogType == "password") {
            this.isOpenChangePassword = true;
            this.title = "修改密码";
          }
          // 进入页面清除之前的定时器
          this.countDownFun(true);
          // 初始化表单数据
          this.initForm();
          this.$message({
            type: "success",
            message: res.msg,
          });
        }
      });
      // 进入页面清除之前的定时器
      this.countDownFun(true);
      // 初始化表单数据
      this.initForm();
      // this.isOpenValidateDialog = false;
      // if (this.dialogType == "phone") {
      //   this.isOpenChangePhone = true;
      //   this.title = "更换手机号";
      // } else if (this.dialogType == "password") {
      //   this.isOpenChangePassword = true;
      //   this.title = "修改密码";
      // }
    },

    // 修改手机号
    changePhone() {
      this.changePhoneForm.formerlyPhone = this.userName;
      updateUserPhone(this.changePhoneForm).then((res) => {
        if (res.code == 200) {
          // 初始化所有弹出框状态
          this.centerDialogVisible = false;
          this.initDialog();
          // 提示成功
          this.$message({
            type: "success",
            message: res.msg + ", 即将退出登录",
          });
          // 定时后退出登录
          setTimeout(() => {
            this.signOut();
          }, 1500);
        } else {
          // 修改失败 提示错误
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },

    // 修改密码
    changePassword() {
      // 表单验证
      this.$refs.changePasswordForm.validate((valid) => {
        if (valid) {
          /**
           * updatePassword
           *
           *  password
           *  userName
           *  passwordSecond
           *  code
           *
           * */
          const updatePwsQuery = {
            code: this.validateForm.code,
            userName: this.userName,
            phonenumber: this.userName,
            password: this.changePasswordForm.password,
            passwordSecond: this.changePasswordForm.confirmPassword,
          };
          updatePassword(updatePwsQuery).then((res) => {
            if (res.code == 200) {
              // 初始化所有弹出框状态
              this.centerDialogVisible = false;
              this.initDialog();
              // 提示成功
              this.$message({
                type: "success",
                message: res.msg + ", 即将退出登录",
              });
              setTimeout(() => {
                this.signOut();
              }, 1500);
            } else {
              // 修改失败 提示错误
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 标题样式
.head-title {
  position: relative;
  font-size: 20px;
  font-family: Source Han Sans CN, Source Han Sans CN-Bold;
  font-weight: bold;
  color: #333;
  padding-bottom: 8px;

  &::before {
    content: "";
    position: absolute;
    left: -0.1429rem;
    bottom: 0;
    width: 7.75rem;
    height: 0.1875rem /* 3/16 */;
    background: #1678ff;
  }
}

// 内容样式
.form-content {
  @apply py-16 w-full;

  .form-sub-title {
    @apply p-2 ml-0 mt-4 mb-8 text-xl border-b border-dashed border-gray-400;

    &:first-child {
      @apply mt-8;
    }
  }
}
</style>
